<template>
  <div class="check-plan-container">
    <h2>盘点计划管理</h2>
    
    <div class="filter-bar">
      <el-input v-model="searchKeyword" placeholder="搜索计划名称" style="width: 300px;" />
      <el-select v-model="statusFilter" placeholder="选择状态">
        <el-option label="全部状态" value="" />
        <el-option label="未开始" value="未开始" />
        <el-option label="进行中" value="进行中" />
        <el-option label="已完成" value="已完成" />
        <el-option label="已取消" value="已取消" />
      </el-select>
      <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" @change="handleDateChange"/>
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button @click="resetFilters">重置</el-button>
      <el-button type="success" @click="createPlan">新建计划</el-button>
    </div>
    
    <el-card>
      <el-table :data="planList" style="width: 100%" border stripe :default-sort="{prop: 'createDate', order: 'descending'}">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="planCode" label="计划编号" width="180" />
        <el-table-column prop="planName" label="计划名称" min-width="200" />
        <el-table-column prop="startDate" label="开始日期" width="150" />
        <el-table-column prop="endDate" label="结束日期" width="150" />
        <el-table-column prop="assetCount" label="资产数量" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="creator" label="创建人" width="100" />
        <el-table-column prop="createDate" label="创建日期" width="150" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="viewPlan(scope.row)">查看</el-button>
            <el-button v-if="scope.row.status === '未开始'" size="small" type="primary" @click="startPlan(scope.row)">开始</el-button>
            <el-button v-if="scope.row.status === '进行中'" size="small" type="success" @click="completePlan(scope.row)">完成</el-button>
            <el-button v-if="['未开始', '进行中'].includes(scope.row.status)" size="small" type="danger" @click="cancelPlan(scope.row)">取消</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
      </div>
    </el-card>
    
    <!-- 创建计划对话框 -->
    <el-dialog v-model="createDialogVisible" title="新建盘点计划" width="600px">
      <el-form :model="newPlan" label-width="100px">
        <el-form-item label="计划名称" required>
          <el-input v-model="newPlan.planName" placeholder="请输入计划名称" />
        </el-form-item>
        <el-form-item label="开始日期" required>
          <el-date-picker v-model="newPlan.startDate" type="date" placeholder="选择开始日期" />
        </el-form-item>
        <el-form-item label="结束日期" required>
          <el-date-picker v-model="newPlan.endDate" type="date" placeholder="选择结束日期" />
        </el-form-item>
        <el-form-item label="盘点范围" required>
          <el-select v-model="newPlan.checkScope" placeholder="选择盘点范围" multiple>
            <el-option label="技术部" value="技术部" />
            <el-option label="市场部" value="市场部" />
            <el-option label="行政部" value="行政部" />
            <el-option label="财务部" value="财务部" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="newPlan.remark" type="textarea" placeholder="请输入备注信息" rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="savePlan">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'CheckPlan',
  data() {
    return {
      //筛选状态
      searchKeyword: '',
      statusFilter: '',
      dateRange: [],   
      currentPage: 1,
      pageSize: 20,
      total: 56,
      //业务状态
      planList: [],
      createDialogVisible: false,
      newPlan: {
        planName: '',
        startDate: '',
        endDate: '',
        checkScope: [],
        remark: ''
      }
    }
  },

  //挂载时加载数据
  mounted() {
    this.loadData()
  },

  methods: {
    loadData() {
      // 模拟数据
      const statuses = ['未开始', '进行中', '已完成', '已取消']
      const departments = ['技术部', '市场部', '行政部', '财务部', '全公司']
      const plans = []
      

      for (let i = 0; i < this.pageSize; i++) {
        const index = (this.currentPage - 1) * this.pageSize + i
        if (index >= this.total) break
        
        //随机从数组中给一个数据
        const status = statuses[Math.floor(Math.random() * statuses.length)]
        
        //添加一条模拟的盘点计划数据
        plans.push({
          id: index + 1,
          planCode: 'PLAN-' + (20240001 + index).toString(),
          planName: departments[Math.floor(Math.random() * departments.length)] + '盘点计划-' + (index + 1),
          startDate: this.generateRandomDate(),
          endDate: this.generateRandomDate(),
          assetCount: Math.floor(Math.random() * 500) + 100,
          status: status,
          creator: '管理员' + (Math.floor(Math.random() * 5) + 1),
          createDate: this.generateRandomDate(),
          remark: '无特殊备注'
        })
      }
      
      this.planList = plans
    },

    //生成随机日期
    generateRandomDate() {
      const start = new Date(2023, 0, 1)
      const end = new Date()
      const randomDate = new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()))
      return randomDate.toISOString().split('T')[0]
    },

    //计划状态（未开始 / 进行中等）映射组件样式类型
    getStatusType(status) {
      switch (status) {
        case '未开始': return 'warning'
        case '进行中': return 'primary'
        case '已完成': return 'success'
        case '已取消': return 'danger'
        default: return 'info'
      }
    },
    handleSearch() {
      console.log('搜索条件:', this.searchKeyword, this.statusFilter, this.dateRange)
      this.currentPage = 1
      this.loadData()
    },
    resetFilters() {
      this.searchKeyword = ''
      this.statusFilter = ''
      this.dateRange = []
      this.loadData()
    },
    handleDateChange() {
      this.handleSearch()
    },
    handleSizeChange(size) {
      this.pageSize = size
      this.loadData()
    },
    handleCurrentChange(current) {
      this.currentPage = current
      this.loadData()
    },
    createPlan() {
      this.newPlan = {
        planName: '',
        startDate: '',
        endDate: '',
        checkScope: [],
        remark: ''
      }
      this.createDialogVisible = true
    },
    savePlan() {
      if (!this.newPlan.planName || !this.newPlan.startDate || !this.newPlan.endDate || this.newPlan.checkScope.length === 0) {
        this.$message.error('请填写必填项')
        return
      }
      console.log('保存计划:', this.newPlan)
      this.createDialogVisible = false
      this.$message.success('计划创建成功')
      this.loadData()
    },
    viewPlan(plan) {
      console.log('查看计划:', plan)
      this.$message.info('查看计划功能待实现')
    },
    startPlan(plan) {
  this.$confirm('确定要开始该盘点计划吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
        console.log('开始计划:', plan)
        this.$message.success('计划已开始')
        this.loadData()
      }).catch(() => {})
    },
    completePlan(plan) {
      this.$confirm('确定要完成该盘点计划吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'success'
      }).then(() => {
        console.log('完成计划:', plan)
        this.$message.success('计划已完成')
        this.loadData()
      }).catch(() => {})
    },
    cancelPlan(plan) {
      this.$confirm('确定要取消该盘点计划吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }).then(() => {
        console.log('取消计划:', plan)
        this.$message.success('计划已取消')
        this.loadData()
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.check-plan-container {
  padding: 20px;
}

.filter-bar {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
  flex-wrap: wrap;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>